package com.rrtv.rpc.core.balancer;

import com.rrtv.rpc.core.common.ServiceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;

/**
 * 轮询算法
 */
public class FullRoundBalance implements LoadBalance {

    private static Logger logger = LoggerFactory.getLogger(FullRoundBalance.class);

    private AtomicInteger index = new AtomicInteger(0);

    @Override
    public ServiceInfo chooseOne(List<ServiceInfo> services) {
        // 为防止多线程情况下，index超出services.size()或不均匀，使用AtomicInteger的getAndUpdate方法
        IntUnaryOperator intUnaryOperator = (x) -> x >= services.size() - 1 ? 0 : x + 1;
        return services.get(index.getAndUpdate(intUnaryOperator));
    }
}
